package src.com.db.httpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public final class WorkerThread implements Runnable {
	private static ServerSocket serverSocket;
	private Socket socket;
	
	public WorkerThread(Socket socket){
		this.socket=socket;
	}
    public static void startPool(int suggestedPort) throws IOException {
        Parameter.setPort(suggestedPort);
        Parameter.print();
        int port = Parameter.getPort();
        int workers = Parameter.getWorkers();
        int timeout = Parameter.getTimeout(); 
        int requestCounter=1;

        // create pool of worker threads
        // create server socket
        // accept connections
        
        Executor pool=Executors.newFixedThreadPool(10);
        
        try{
    		serverSocket=new ServerSocket(port);
    		while (true){
    			System.out.println("Waiting for connection");
    			Socket socket =serverSocket.accept();
    			socket.setSoTimeout(1000);
    			System.out.println("Handled "+requestCounter+" request");
    			requestCounter++;
    			pool.execute(new WorkerThread(socket));
    		}
    		
    	} catch (IOException e){
    		System.out.println("IOException");
    	}
    }

    public void run() {
    	Worker worker=new Worker();
    	
    	try {
    	
    			
    			new Worker().handleRequest(socket);
    		
		} catch (IOException e) {
			System.out.println("IOException on server in client listening");
			e.printStackTrace();
		}
    	
    	
    	
    	
    	 
    	 
         
    }
}